package com.Servlet;

import com.entity.User;
import com.service.UserService;
import com.service.impl.UserServiceImpl;
import com.util.MyUtil;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "Servlet.UserServlet", value = "/login")
public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       request.setCharacterEncoding("utf-8");
        UserService service = new UserServiceImpl();
        String uname = request.getParameter("uname");
        String pwd = request.getParameter("pwd");
        String code = request.getParameter("code");

        HttpSession session = request.getSession();
        String validateCode = (String) session.getAttribute("code");

        if(MyUtil.isEmpty(validateCode)){
//            重定向到登录页面
            response.sendRedirect(request.getContextPath()+"/login.html");
            return;
        }

        //判断验证码是否正确
        if(!code.equals(validateCode)){
            //重定向到登录页面
            response.sendRedirect(request.getContextPath()+"/login.html");
            return;
        }

        //判断用户名密码是否为空
        if(MyUtil.isEmpty(uname) || MyUtil.isEmpty(pwd)){
            response.sendRedirect(request.getContextPath()+"/login.html");
            return;
        }

        boolean re = service.selectUser1("uname", "pwd");
        if (re){
            session.setAttribute("uname",uname);
            response.sendRedirect(request.getContextPath()+"/bookList");
        }else {
            response.sendRedirect(request.getContextPath()+"/login.jsp");
        }
    }
}
